package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

@Slf4j
@Component
public class CacheClient {
    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    private  final StringRedisTemplate stringRedisTemplate;
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //将数据加入redis，并设置有效期
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    //将数据加入redis，设置逻辑过期时间
    public void setWithLogicalExpire(String key, Object value, Long time,TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }
    //传入空值来解决缓存穿透
    public <T,ID> T queryWithPassThrough(String keyprefit, ID id, Class<T> type, Function<ID,T> dbFallback, Long time, TimeUnit unit) {
        // 从redis中查询缓存数据
        String key= keyprefit + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        T t= null;
        //判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            t = JSONUtil.toBean(shopJson,type);
            return t;
        }
        if(shopJson!=null) {
            return null;
        }
        // 缓存未命中，从数据库中进行操作
        t = dbFallback.apply(id);
        //不存在将空值写入redis
        if (t == null) {
            stringRedisTemplate.opsForValue().set(key, "", CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key,t, time, unit);
        return t;
    }
    //逻辑过期解决缓存击穿
    public <T,ID> T queryWithLogicalExpire(String keyprefit,ID id,Class<T> type,Function<ID,T> dbFallback, Long time, TimeUnit unit) {
        String key= keyprefit + id;
        // 从redis中查询缓存数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        T t = null;
        //判断缓存是否存在
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        //判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        t = JSONUtil.toBean(data,type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期，直接返回
            return t;
        }
        //已过期尝试获取互斥锁
        String key1= "lock:shop:"+id;
        boolean flag= tryLock(key1);
        if(flag){
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    T t1 = dbFallback.apply(id);
                    this.setWithLogicalExpire(key,t1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(key1);
                }
            });
        }
        // 3、获取锁失败，再次查询缓存，判断缓存是否重建（这里双检是有必要的）
        shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(shopJson)) {
            // 3.1 缓存未命中，直接返回失败信息
            return null;
        }
        // 3.2 缓存命中，将JSON字符串反序列化未对象，并判断缓存数据是否逻辑过期
        redisData = JSONUtil.toBean(shopJson, RedisData.class);
        // 这里需要先转成JSONObject再转成反序列化，否则可能无法正确映射Shop的字段
        data = (JSONObject) redisData.getData();
        t = JSONUtil.toBean(data, type);
        expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 当前缓存数据未过期，直接返回
            return t;
        }
        // 4、返回过期数据
        return t;

    }
    //获取锁
    private Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //拆箱要判空避免npe
        return Boolean.TRUE.equals(flag);
    }
    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
